import React, { useState, useEffect, useRef } from 'react'
import MyNavBar from '../../components/MyNavBar'
import { Toast } from 'antd-mobile'
import { setLocalCity, getCurrentCity } from '../../utils/city'
import { getCityList, getHotCityList } from '../../api/city'
import { AutoSizer, List } from 'react-virtualized'
import styles from './index.module.scss'

// 标题的高度
const TITLE_HEIGHT = 36
// 每行数据的高度
const ROW_HEIGHT = 50
// 有房源的城市列表
const HAVECITY = ['北京', '上海', '广州', '深圳']

function CityList({ history }) {
  // 左边城市列表对象数据
  const [cityListObj, setCityListObj] = useState({})
  // 右边城市索引列表
  const [cityIndexList, setCityIndexList] = useState([])
  // 选中的城市索引
  const [citySelectIndex, setCitySelectIndex] = useState(0)
  // 创建List的ref
  const listRef = useRef()

  // 获取城市列表数据(城市列表、热门城市、定位城市)
  const getCityListData = async () => {
    const res1 = await getCityList()
    const res2 = await getHotCityList()

    // 临时左边城市列表对象数据
    const tempObj = {}
    // 临时右边城市列表索引数据
    let tempIndexList = []

    // 处理城市列表数据
    res1.data.body.forEach((city) => {
      // 获取首字母
      const letter = city.short.substr(0, 1)
      if (tempObj[letter]) {
        // 存在
        tempObj[letter].push(city)
      } else {
        // 不存在
        tempObj[letter] = [city]
      }
    })

    tempIndexList = Object.keys(tempObj).sort()

    // 处理热门城市数据
    tempObj['hot'] = res2.data.body
    tempIndexList.unshift('hot')

    // 定位城市
    const currentCity = await getCurrentCity()
    tempObj['#'] = [currentCity]
    tempIndexList.unshift('#')

    setCityListObj(tempObj)
    setCityIndexList(tempIndexList)
  }

  useEffect(() => {
    getCityListData()
  }, [])

  const formatterLetter = (letter) => {
    switch (letter) {
      case '#':
        return '定位城市'

      case 'hot':
        return '热门城市'

      default:
        return letter.toUpperCase()
    }
  }

  // 城市切换选择
  const toggleSelectCity = ({ label, value }) => {
    if (!HAVECITY.includes(label)) {
      Toast.info('该城市暂无房源哦~', 1.5)
      return
    }

    setLocalCity({ label, value })

    history.go(-1)
  }

  // 渲染每一行
  const rowRenderer = ({ key, index, style }) => {
    const letter = cityIndexList[index]
    const list = cityListObj[letter]
    return (
      <div key={key} style={style} className={styles.city}>
        <div className={styles.title}>{formatterLetter(letter)}</div>
        {list.map((item) => {
          return (
            <div
              onClick={() => toggleSelectCity(item)}
              key={item.value}
              className={styles.name}
            >
              {item.label}
            </div>
          )
        })}
      </div>
    )
  }

  // 计算每行的高度
  const calcRowHeight = ({ index }) => {
    const letter = cityIndexList[index]
    const list = cityListObj[letter]

    return TITLE_HEIGHT + list.length * ROW_HEIGHT
  }

  const toggleSelect = (index) => {
    listRef.current.scrollToRow(index)
  }

  // 渲染右边索引
  const renderCityListIndex = () => {
    return (
      <div className={styles.cityIndex}>
        {cityIndexList.map((item, index) => {
          return (
            <div key={item} className={styles.cityIndexItem}>
              <span
                className={index === citySelectIndex ? styles.indexActive : ''}
                onClick={() => toggleSelect(index)}
              >
                {item === 'hot' ? '热' : item.toUpperCase()}
              </span>
            </div>
          )
        })}
      </div>
    )
  }

  // 滚动
  const onRowsRendered = ({ startIndex }) => {
    setCitySelectIndex(startIndex)
  }

  return (
    <div className={styles.citylist}>
      <MyNavBar>城市选择</MyNavBar>
      <AutoSizer>
        {({ height, width }) => (
          <List
            ref={listRef}
            width={width}
            height={height}
            rowCount={cityIndexList.length}
            rowHeight={calcRowHeight}
            rowRenderer={rowRenderer}
            onRowsRendered={onRowsRendered}
            scrollToAlignment="start"
          />
        )}
      </AutoSizer>
      {renderCityListIndex()}
    </div>
  )
}

export default CityList
